<template>
  <div class="app-container bg-white">
    <!-- 页面头部 -->

    <!-- 页面内容 -->
    <div class="page-body">
      <el-form size="small" :inline="true">
        <el-form-item>
          <el-input size="small" placeholder="请输入商品品牌" v-model.trim="queryName" maxlength="25" clearable></el-input>
        </el-form-item>
        <el-form-item>
          <el-date-picker size="small" v-model="queryTime" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" :value-format="'yyyy-MM-dd'"></el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button size="small" class="width_104" type="primary" @click="getPageDataList()">查询</el-button>
          <el-button size="small" class="width_104" @click="resetOption()">重置</el-button>
        </el-form-item>
      </el-form>
      <div>
        <el-button size="mini" type="success" icon="el-icon-document-add" @click="addOrEditOption()" v-if="roleBtns.includes('sys:brand:save') || $store.getters.isAdmin">新建品牌</el-button>
        <el-button size="mini" type="primary" icon="el-icon-download" @click="exportOption()" class="fr">批量导出</el-button>
        <el-button size="mini" type="danger" icon="el-icon-delete" @click="removeOption()" v-if="roleBtns.includes('sys:brand:remove') || $store.getters.isAdmin">批量删除</el-button>
      </div>
      <el-table class="margin_top_20" :data="pageData" stripe :header-cell-style="tableHeaderStyle" v-loading="loading" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="42"></el-table-column>
        <el-table-column prop="status" label="品牌图片">
          <template slot-scope="scope">
            <el-image class="my_img" v-if="scope.row.imgUrl" :src="imgBaseUrl + scope.row.imgUrl" lazy fit="cover"></el-image>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="品牌名称">
          <template slot-scope="scope">
            <div class="text-ellipsis_2" :title="scope.row.name">{{scope.row.name}}</div>
          </template>
        </el-table-column>
        <el-table-column prop="brandNo" label="品牌编码"></el-table-column>
        <el-table-column prop="userName" label="创建人"></el-table-column>
        <el-table-column prop="createTime" label="创建时间"></el-table-column>
        <el-table-column prop="status" label="是否启用">
          <template slot-scope="scope">
            <el-switch @change="changeBrandStatus(scope.row, scope.$index)" :value="scope.row.statusBoolean" :disabled="!(roleBtns.includes('sys:brand:update') || $store.getters.isAdmin)"></el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="name" label="资料包">
          <template slot-scope="scope">
            <img src="http://ehrhz.oss-cn-hangzhou.aliyuncs.com/carhr/carhrwechat/carhrImages/carhrImg/carhr-schImg/icon/icon-system-file-thumb.svg" width="30">
            <div class="pointer text-brand" @click="openDownload(scope.row.id)">下载</div>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180">
          <template slot-scope="scope">
            <button class="my-btn my-btn--mini my-btn--primary plain" @click="addOrEditOption(scope.row.id)" v-if="roleBtns.includes('sys:brand:update') || $store.getters.isAdmin">编辑</button>
            <button class="my-btn my-btn--mini my-btn--danger plain" @click="removeItemsOption([scope.row.id])" v-if="roleBtns.includes('sys:brand:remove') || $store.getters.isAdmin">删除</button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 页面页脚 -->
    <div class="text-center">
      <el-pagination background @size-change="handleSizeChange" @current-change="handlePagingChange" :current-page="pageIndex" :page-sizes="pageSizes"
        :page-size="pageSize" :layout="paginationLayout" :total="pageCount">
      </el-pagination>
    </div>

    <brand-file :visible.sync="isShowModal" :brand-id="showBrandId"></brand-file>
  </div>
</template>

<script>
import Setting from '@/settings';
import { mapGetters } from 'vuex';
import BrandFile from '@/views/store-management/components/brandFile';
import { GetStoreBrandListByParams, RemoveStoreBrandItem, ChangeStoreBrandItemStatus, ExportStoreBrandList } from '@/views/store-management/services/index';

export default {
  name: 'StoreBrand',
  components: {
    BrandFile
  },
  data() {
    return {
      queryName: '',
      queryTime: [],
      pageIndex: 1,
      pageSize: Setting.defaultTablePaginationSize,
      pageSizes: Setting.tablePaginationSizes,
      tableHeaderStyle: Setting.tableHeaderStyle,
      paginationLayout: Setting.tablePaginationLayout,
      pageData: [],
      pageCount: 0,
      loading: false,
      multipleSelection: [],
      showBrandId: null,
      isShowModal: false,
      isEditMode: false,
      imgBaseUrl: `${process.env.VUE_APP_FILE_URL}/`
    }
  },
  computed: {
    ...mapGetters(['roleBtns']),
    title() {
      if (!this.isEditMode) {
        return '新建品牌';
      } else {
        return '编辑品牌';
      }
    }
  },
  activated() {
    this.getPageDataList();
  },
  created() {
    this.getPageDataList();
  },
  methods: {
    exportOption() {
      // if (!this.multipleSelection || !this.multipleSelection.length) {
      //   this.$message.warning('请选择需要导出的商品品牌!');
      //   return;
      // }
      this.loading = true;
      const searchData = {
        search: this.queryName,
        startTime: this.queryTime[0] ? this.queryTime[1] : '',
        endTime: this.queryTime[1] ? this.queryTime[1] : '',
        targetIds: this.multipleSelection.map(item => item.id).join(',')
      };

      this.blobAxiosApi('get', '/cloudApi/goods/goodsBrand/exportGoodsBrand', searchData, '商品品牌导出文件.xlsx')
      .finally(() => this.loading = false)
    },
    openDownload(rowId) {
      this.showBrandId = rowId;
      this.isShowModal = true;
    },
    handleSelectionChange(selectlist) {
      this.multipleSelection = selectlist;
    },
    // 新增和编辑按钮
    addOrEditOption(rowId) {
      if (rowId) {
        this.$router.push({
          name: 'StoreBrandEdit',
          query: { id: rowId }
        })
      } else {
        this.$router.push({
          name: 'StoreBrandAdd'
        })
      }
    },
  
    // 修改品牌上下架状态
    changeBrandStatus(row, index) {
      this.loading = true;
      row.status = Number(row.status) == 0 ? 1 : 0;
      ChangeStoreBrandItemStatus({
        id: row.id,
        status: row.status
      })
      .finally(() => this.loading = false)
      .then(data => {
        if (data.code == 200) {
          // this.$set(this.pageData, index, row);
          this.$message.success(row.status ? '启用成功!' : '禁用成功!');
          row.statusBoolean = !row.statusBoolean;
        } else {
          this.$message.error(row.status ? '启用失败!' : '禁用失败!');
        }
      })
      .catch(error => {
        this.$message.error(row.status ? '启用失败!' : '禁用失败!');
      })
    },

    removeOption() {
      if (!this.multipleSelection || !this.multipleSelection.length) {
        this.$message.warning('请选择需要删除的用户!');
        return;
      }
      this.removeItemsOption(this.multipleSelection.map(item => item.id));
    },
    removeItemsOption(nodeIds) {
      this.$confirm('此操作将永久删除该品牌, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        closeOnClickModal: false,
        closeOnPressEscape: false,
        type: 'warning',
        beforeClose: (action, instance, done) => {
          if (action === 'confirm') {
            instance.confirmButtonLoading = true;
            RemoveStoreBrandItem({ targetIds: nodeIds.join(',') })
              .then(data => {
                instance.confirmButtonLoading = false;
                if (data.code == 200) {
                  this.$message.success('删除成功!');
                  done()
                } else {
                  this.$message.success('删除失败!');
                }
              })
              .catch(error => {
                instance.confirmButtonLoading = false;
              })
          } else {
            done();
          }
        }
      }).then(() => {
        this.getPageDataList();
      })
    },

    // 重置操作
    resetOption() {
      this.queryName = '';
      this.queryTime = [];
      this.pageIndex = 1;
      this.getPageDataList();
    },

    // 获取页面列表数据
    getPageDataList() {
      this.loading = true;
      GetStoreBrandListByParams({
        search: this.queryName,
        startTime: this.queryTime && this.queryTime[0] ? this.queryTime[0] : '',
        endTime: this.queryTime && this.queryTime[1] ? this.queryTime[1] : '',
        pageSize: this.pageSize,
        pageNum: this.pageIndex
      })
      .finally(() => this.loading = false)
      .then(data => {
        if (data.code == 200) {
          this.pageData = (data.data.list && data.data.list.length) ? data.data.list.map(item => {
            item.statusBoolean = !!item.status;
            return item;
          }) : [];
          this.pageCount = data.data.total;

          if ((!data.data.list || !data.data.list.length) && this.pageIndex > 1) {
            this.pageIndex = 1;
            this.getPageDataList();
          }
        }
      })
    },
    // 分页列表改变
    handlePagingChange(event) {
      this.pageIndex = event;
      this.getPageDataList();
    },
    handleSizeChange(event) {
      this.pageIndex = 1;
      this.pageSize = event;
      this.getPageDataList();
    }
  }
}
</script>
<style lang="scss" scoped>
.my_img {
  max-width: 80px;
  max-height: 80px;
  vertical-align: middle;
}

::v-deep .el-date-editor .el-range-separator {
  width: auto;
}

.width_104 {
  width: 104px;
}
</style>
